package com.example.itshome.network;

import com.example.itshome.activity.SetPageActivity;
import com.example.itshome.manager.UserInfoManager;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class UploadFileRequest {

    private static final String BOUNDARY = "----WebKitFormBoundaryT1HoybnYeFOGFlBR";

    public static void uploadForm(Map<String, String> params, String fileFormName,
                                  File uploadFile,String uri,Runnable run){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    uploadFormPrivate(params,fileFormName,uploadFile,uri);
                    if(run!=null){
                        run.run();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private static void uploadFormPrivate(Map<String, String> params, String fileFormName,
                           File uploadFile,String uri)
            throws IOException {


        StringBuilder sb = new StringBuilder();
        /*
          普通的表单数据
         */
        for (String key : params.keySet()) {
            sb.append("--" + BOUNDARY + "\r\n");
            sb.append("Content-Disposition: form-data; name=\"").append(key).append("\"").append("\r\n");
            sb.append("\r\n");
            sb.append(params.get(key)).append("\r\n");
        }
        /*
          上传文件的头
         */
        sb.append("--" + BOUNDARY + "\r\n");
        sb.append("Content-Disposition: form-data; name=\"").append(fileFormName)
                .append("\"; filename=\"")
                .append(uploadFile.getName()).append("\"")
                .append("\r\n");
        sb.append("Content-Type: image/jpeg" + "\r\n");// 如果服务器端有文件类型的校验，必须明确指定ContentType
        sb.append("\r\n");

        byte[] headerInfo = sb.toString().getBytes(StandardCharsets.UTF_8);
        byte[] endInfo = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(StandardCharsets.UTF_8);
        System.out.println(sb.toString());
        URL url = new URL("http://101.43.242.216:18950/"+uri);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type",
                "multipart/form-data; boundary=" + BOUNDARY);
        conn.setRequestProperty("Content-Length", String
                .valueOf(headerInfo.length + uploadFile.length()
                        + endInfo.length));
        conn.setRequestProperty("Authorization", UserInfoManager.getInstance().getTokenRequest());
        conn.setDoOutput(true);

        OutputStream out = conn.getOutputStream();
        InputStream in = new FileInputStream(uploadFile);
        out.write(headerInfo);

        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) != -1)
            out.write(buf, 0, len);

        out.write(endInfo);
        in.close();
        out.close();
        if (conn.getResponseCode() == 200) {
            System.out.println("上传成功");
        }

    }
}